--[[
	The Argot marshalling routines for a booklist.
	
	A maximum of 256 books can be stored as only a u8
	is used for the array length. 
  ]]

require "argot"

BookArrayArgot = { TYPENAME = argot.TypeName('booklist') }
BookArrayArgot_mt = { __index = BookArrayArgot }

function BookArrayArgot.create(self)
	local attributes = {}
    setmetatable( attributes, BookArrayArgot_mt )
    return attributes
end

function BookArrayArgot.write(out, books, element)
    out:write_named_object( argot.uint8_name, table.getn(books) )
    print('Writing books')
    for key, book in ipairs(books) do
        out:write_named_object( argot.TypeName('book'), book)
    end
end

function BookArrayArgot.read(instream, element)

	-- crash code
	print('A', instream, element)
	local xxx = {}; table.insert(xxx, 'X')
	print('B')


    instream:read_named_object( argot.uint8_name )
    local size = instream.stack.u8
    local books = {}

	for i = 1, size do
        print('Reading book')
        instream:read_named_object(argot.TypeName('book'))
        print('done reading book')
        obj = item_get_object(instream.stack.top)
        -- print('obj ', obj)
        table.insert(books, obj)
    end

	-- print('xxx', books)
    instream.stack:set_object( element, books )
    
    return argot.TYPE_OK
end